<template>
  <el-card class="my-invite-panel mb-4" shadow="never" v-if="experts.length > 0">
    <div class="panel-title-row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
      <div class="panel-title" style="flex:4">你可以邀请下面用户，快速获得回答</div>
      <el-input
        style="flex:2"
          v-model="name"
          placeholder="搜索你想邀请的人"
          class="invite-search-input"
          clearable
          prefix-icon="el-icon-search"
        />
    </div>
      <div v-for="expert in pagedExperts" :key="expert.id" class="expert-item flex items-center justify-between py-2 px-2 rounded-lg hover:bg-blue-50 transition">
        <!-- <div v-for="expert in pagedExperts" :key="expert.id" class="expert-item flex items-center justify-between py-2 px-2 rounded-lg hover:bg-blue-50 transition"> -->
        <div class="flex items-center gap-3 min-w-0">
          <img :src="expert.avatar" class="w-10 h-10 rounded-full object-cover border border-blue-100 shadow-sm" />
          <div class="min-w-0">
            <div class="font-medium text-base text-blue-900 truncate">{{ expert.name }}
              <el-tag v-if="expert.online" size="small" type="success" class="ml-2">在线</el-tag>
              <el-tag v-else size="small" type="info" class="ml-2">离线</el-tag>
            </div>
            <div class="text-xs text-gray-500 truncate">{{ expert.org }} · {{ expert.title }}</div>
            <div class="flex flex-wrap gap-1 mt-1">
              <el-tag v-for="(tag,index) in expert.tags" :key="tag" size="small" 
              :type="tagTypes[index % tagTypes.length]"
              type="warning">{{ tag }}</el-tag>
            </div>
            <div class="text-xs text-gray-500 mt-1 truncate">TA已帮助{{expert.answerCount}}人获得解答</div>

          </div>
        </div>
        <div class="min-w-0">
            <!-- <div class="font-medium text-base text-blue-900 truncate">{{ user.name }}</div> -->
            <!-- <div class="text-xs text-gray-500 truncate">已回答100人</div> -->
          </div>
        <div class="flex gap-2">
        <el-button size="small" type="primary" round :disabled="expert.invited" @click="handleInviteUser(expert)">{{ expert.invited ? '已邀请' : '邀请回答' }}</el-button>

          <!-- <el-button size="small" type="primary" :disabled="!expert.online" @click="startAudioMeeting(expert)">音频答疑</el-button>
          <el-button size="small" type="success" :disabled="!expert.online" @click="startVideoMeeting(expert)">视频答疑</el-button>
          <el-button size="small" type="info" @click="startTextChat(expert)">文字答疑</el-button> -->
        </div>
      </div>
    <!-- </div> -->
    <div v-if="pagedExperts.length === 0" class="text-gray-400 text-center py-4">暂无邀请的专家</div>
    <el-button  v-if="pagedExperts && pagedExperts.length>5" size="small" @click="handleChangePage">换一换</el-button>
  </el-card>

  <!-- 音视频会议弹框 -->
  <el-dialog
    v-model="showMeeting"
    :title="meetingTitle"
    width="90%"
    :close-on-click-modal="false"
    :show-close="false"
    destroy-on-close
    class="meeting-dialog"
  >
    <VideoMeeting
      :room-name="meetingRoom"
      :display-name="currentUser.name"
      :meeting-title="meetingTitle"
      :is-audio-only="isAudioOnly"
      @end-meeting="handleMeetingEnd"
    />
  </el-dialog>

  <!-- 文字聊天对话框 -->
  <!-- <el-dialog
    v-model="showChat"
    :title="`与 ${selectedExpert?.name || ''} 的对话`"
    width="800px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="chat-dialog-content">
      <TextChat
        ref="textChatRef"
        :current-user="currentUser"
        :other-user="selectedExpert"
        @send-message="handleSendMessage"
      />
    </div>
  </el-dialog> -->
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import VideoMeeting from '@/components/meeting/VideoMeeting.vue'
import TextChat from '@/components/chat/TextChat.vue'
import { useChatStore } from '@/stores/chatStore'
import wsClient, { MessageType } from '@/utils/websocket'
import * as chatApi from '@/axios/api/chat'
import { get, post } from '@/axios/utils/request'

// expert/recommend

// specialtyTagIds

const props = defineProps({
  question: {
    type: Object,
    default: () => {}
  }
})

// console.log(props.question.specialtyTagIds);

const experts = ref([])
const onlineData = ref([])
const pageIndex = ref(0)
const pageSize = 5
const pagedExperts = ref([])
const invitedMap = ref({}) // 记录已邀请状态
const name = ref(null)
const tagTypes = [
  'primary',   // 蓝色
  'success',   // 绿色
  'warning',   // 橙色
  'danger',    // 红色
  'info',      // 紫色
  'primary',   // 蓝色
  'success',   // 绿色
  'warning',   // 橙色
  'danger',    // 红色
  'info'       // 紫色
]
// 监听搜索输入
let searchTimer = null
watch(name, (newVal) => {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    getExperInfo(newVal)
    updatePagedExperts()

  }, 300)
})
// 计算当前页专家
function updatePagedExperts() {
  // 标记在线状态
  const onlineUids = new Set((onlineData.value || []).map(item => item))
  experts.value.forEach(expert => {
    expert.online = onlineUids.has(expert.uid+'')
    // 保持已邀请状态
    expert.invited = !!invitedMap.value[expert.id]
  })
  console.log(onlineData.value.includes('5'));
  console.log(onlineData.value);

  // 分页
  const start = pageIndex.value * pageSize
  pagedExperts.value = experts.value.slice(start, start + pageSize)
}

// 换一换
function handleChangePage() {
  const totalPages = Math.ceil(experts.value.length / pageSize)
  pageIndex.value = (pageIndex.value + 1) % totalPages
  updatePagedExperts()
}

// 邀请专家
async function handleInviteUser(expert) {
  invitedMap.value[expert.id] = true
  expert.invited = true

  //question/invite
  const res = await get('question/invite', {
    questionId: props.question.id,
    uid: expert.uid,
  })
  if (res.code === 0) {
    ElMessage.success('邀请成功')
  } else {
    ElMessage.error(res.msg)
  } 
  updatePagedExperts()
  // 触发原有事件
  // $emit('inviteUser', expert) // 若有emit
}

const chatStore = useChatStore()
const currentUser = computed(() => chatStore.loginUserInfo)

// 会议相关
const showMeeting = ref(false)
const meetingRoom = ref('')
const meetingTitle = ref('')
const isAudioOnly = ref(false)

// 文字聊天相关
const showChat = ref(false)
const selectedExpert = ref(null)
const textChatRef = ref(null)


onMounted(async () => {
  onlineData.value = JSON.parse(sessionStorage.getItem('onlineData')) || [];
  // 注册WebSocket事件处理器
  wsClient.on(MessageType.CHAT, handleChatMessage)
  wsClient.on(MessageType.MEETING_INVITE, handleMeetingInvite)
  wsClient.on(MessageType.MEETING_ACCEPT, handleMeetingAccept)
  wsClient.on(MessageType.MEETING_REJECT, handleMeetingReject)
  wsClient.on(MessageType.MEETING_END, handleMeetingEndMessage)
  wsClient.on(MessageType.COUNT, handleOnlineCount)
  // 初始加载专家列表
  getExperInfo()
  updatePagedExperts()
})

watch(onlineData, updatePagedExperts)
watch(experts, updatePagedExperts)

onBeforeUnmount(() => {
  // 清除搜索定时器
  if (searchTimer) clearTimeout(searchTimer)

  // 移除WebSocket事件处理器
  wsClient.off(MessageType.CHAT, handleChatMessage)
  wsClient.off(MessageType.MEETING_INVITE, handleMeetingInvite)
  wsClient.off(MessageType.MEETING_ACCEPT, handleMeetingAccept)
  wsClient.off(MessageType.MEETING_REJECT, handleMeetingReject)
  wsClient.off(MessageType.MEETING_END, handleMeetingEndMessage)
  wsClient.off(MessageType.COUNT, handleOnlineCount)
})

async function  getExperInfo(name) {
  // 获取推荐专家
      console.log('props.question==========================');
      console.log(props.question);
      console.log(props.question.specialtyTagIds);
      console.log('props.question==========================');


  if (props.question && props.question.specialtyTagIds) {
    console.log(props.question.specialtyTagIds);
    try {
      console.log(props.question);
      
      const res = await get('expert/recommend', { specialtyTagIds: props.question.specialtyTagIds,name: name || '',questionId: props.question.id,uid: props.question.uid })
      if (res.code === 0 && Array.isArray(res.data)) {
        experts.value = res.data.map(item => ({
          id: item.id,
          uid: item.uid,
          name: item.name,
          avatar: item.avatar,
          org: item.orgName,
          title: item.honor,
          tags:item.specialtyTagNames,
          online: onlineData.value.includes(item.uid+''),
          invited: false,
          answerCount: item.answerCount
        }))
        
      } else {
        experts.value = []
      }

    } catch (e) {
      experts.value = []
    }
  }
}


// 重命名为handleMeetingEndMessage
function handleOnlineCount(data) {
  console.log(data);
  onlineData.value = data
}

// 开始音频会议
async function startAudioMeeting(expert) {
  if (!expert.online) return
  
  try {
    isAudioOnly.value = true
    meetingRoom.value = `meeting_${Date.now()}_${expert.id}`
    meetingTitle.value = `与 ${expert.name} 的音频答疑`
    
    // 发送会议邀请
    await chatApi.sendMeetingInvite({
      expertId: expert.id,
      roomName: meetingRoom.value,
      type: 'audio'
    })
    
    // 通过WebSocket通知专家
    wsClient.send(MessageType.MEETING_INVITE, {
      type: 'audio',
      expert,
      roomName: meetingRoom.value
    })
    
    showMeeting.value = true
    selectedExpert.value = expert
    
    ElMessage.success('已发送音频会议邀请')
  } catch (error) {
    console.error('发起音频会议失败:', error)
    ElMessage.error('发起音频会议失败')
  }
}

// 开始视频会议
async function startVideoMeeting(expert) {
  if (!expert.online) return
  
  try {
    isAudioOnly.value = false
    meetingRoom.value = `meeting_${Date.now()}_${expert.id}`
    meetingTitle.value = `与 ${expert.name} 的视频答疑`
    
    // 发送会议邀请
    await chatApi.sendMeetingInvite({
      expertId: expert.id,
      roomName: meetingRoom.value,
      type: 'video'
    })
    
    // 通过WebSocket通知专家
    wsClient.send(MessageType.MEETING_INVITE, {
      type: 'video',
      expert,
      roomName: meetingRoom.value
    })
    
    showMeeting.value = true
    selectedExpert.value = expert
    
    ElMessage.success('已发送视频会议邀请')
  } catch (error) {
    console.error('发起视频会议失败:', error)
    ElMessage.error('发起视频会议失败')
  }
}

// 开始文字聊天
async function startTextChat(expert) {
  try {
    selectedExpert.value = expert
    showChat.value = true
    
    // 加载历史消息
    const { data } = await chatApi.getChatHistory({
      expertId: expert.id,
      page: 1,
      pageSize: 50
    })
    
    // 将历史消息添加到聊天窗口
    if (data.messages) {
      data.messages.forEach(message => {
        if (textChatRef.value) {
          textChatRef.value.receiveMessage({
            ...message,
            isSelf: message.senderId === currentUser.value.id
          })
        }
      })
    }
  } catch (error) {
    console.error('加载聊天记录失败:', error)
    ElMessage.error('加载聊天记录失败')
  }
}

// 处理会议结束
async function handleMeetingEnd(data) {
  try {
    showMeeting.value = false
    meetingRoom.value = ''
    
    // 保存会议记录
    await chatApi.saveMeetingRecord({
      type: isAudioOnly.value ? 'audio' : 'video',
      expertId: selectedExpert.value.id,
      duration: data.duration,
      startTime: data.startTime
    })
    
    // 通知专家会议结束
    wsClient.send(MessageType.MEETING_END, {
      expert: selectedExpert.value,
      roomName: meetingRoom.value
    })
    
    ElMessage.success('会议已结束')
  } catch (error) {
    console.error('保存会议记录失败:', error)
    ElMessage.error('保存会议记录失败')
  }
}

// 处理发送消息
async function handleSendMessage(message) {
  try {
    // 如果是图片或文件消息，先上传
    if (message.type === 'image') {
      const formData = new FormData()
      formData.append('file', message.file)
      const { data } = await chatApi.uploadChatImage(formData)
      message.content = data.url
    } else if (message.type === 'file') {
      const formData = new FormData()
      formData.append('file', message.file)
      const { data } = await chatApi.uploadChatFile(formData)
      message.content = data.url
    }
    
    // 通过WebSocket发送消息
    wsClient.send(MessageType.CHAT, {
      ...message,
      to: selectedExpert.value.id
    })
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// WebSocket消息处理函数
function handleChatMessage(message) {
  if (textChatRef.value) {
    textChatRef.value.receiveMessage({
      ...message,
      isSelf: false
    })
  }
}

function handleMeetingInvite(data) {
  ElMessage.info(`收到来自 ${data.expert.name} 的${data.type === 'audio' ? '音频' : '视频'}会议邀请`)
}

function handleMeetingAccept(data) {
  ElMessage.success(`${data.expert.name} 已接受会议邀请`)
}

function handleMeetingReject(data) {
  ElMessage.warning(`${data.expert.name} 已拒绝会议邀请`)
  showMeeting.value = false
  meetingRoom.value = ''
}

// 重命名为handleMeetingEndMessage
function handleMeetingEndMessage(data) {
  if (data.roomName === meetingRoom.value) {
    showMeeting.value = false
    meetingRoom.value = ''
    ElMessage.info('会议已结束')
  }
}
</script>

<style scoped>
.my-invite-panel {
  border-radius: 14px;
  background: linear-gradient(135deg, #fafdff 0%, #e3f0ff 100%);
  border: none;
  box-shadow: 0 2px 10px 0 rgba(56,112,255,0.07);
  padding: 18px 18px 10px 18px;
}
.panel-title {
  font-size: 17px;
  font-weight: 600;
  color: #1a237e;
  margin-bottom: 10px;
}
.expert-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.expert-item {
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 1px 4px 0 rgba(56,112,255,0.04);
  margin-bottom: 2px;
  transition: box-shadow 0.16s, background 0.16s;
}
.expert-item:hover {
  box-shadow: 0 4px 16px 0 rgba(56,112,255,0.10);
  background: #f0f6ff;
}
.chat-dialog-content {
  height: 600px;
}

:deep(.el-dialog__body) {
  padding: 0;
  height: 600px;
}
</style>